import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/models/report/classStudentReportResult.dart';
import 'package:ichinesereader/pages/teacher/homeworkProgress.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import '../../themes/pageStyles.dart';

// ignore: must_be_immutable
class CurrentHomeworkDataGrid extends StatelessWidget {
  CurrentHomeworkDataGrid(this.assignmentItems);

  List<ListAssingmentElement> assignmentItems;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();
  final PageStyles _pageStyles = PageStyles();

  @override
  Widget build(BuildContext context) {
    Log.debug('build CurrentHomeworkDataGrid');

    return this.assignmentItems.isNotEmpty
        ? Column(children: [Expanded(child: _buildDataGrid())])
        : Center(child: Text('Data not available ...'));
  }

  Container _buildDataGrid() {
    return Container(
      decoration: _pageStyles.dataGridBackground(),
      child: Container(
        margin: EdgeInsets.all(12.0),
        decoration: _pageStyles.dataGridForground(),
        child: SfDataGrid(
          source: AssignmentDataGridSource(items: assignmentItems),
          onQueryRowHeight: (row) {
            return row.rowIndex == 0 ? 50.0 : 49.0;
          },
          //设置表头高度
          allowSorting: true,
          allowTriStateSorting: true,
          allowSwiping: false,
          controller: _dataGridController,
          navigationMode: GridNavigationMode.row,
          endSwipeActionsBuilder:
              (BuildContext context, DataGridRow row, int rowIndex) {
            return GestureDetector(
                onTap: () {},
                child: Container(
                    color: Colors.redAccent,
                    child: Center(
                      child: Icon(Icons.delete),
                    )));
          },
          columns: <GridColumn>[
            GridColumn(
              width: 180,
              columnName: 'Task',
              label: buildDataGridColumnLabel('Task'),
            ),
            GridColumn(
              columnName: 'Status',
              width: isWebOrDesktop ? 120 : 120,
              label: buildDataGridColumnLabel('Status'),
            ),
            GridColumn(
              columnName: 'OverallProgress',
              width: isWebOrDesktop ? 120 : 120,
              label: buildDataGridColumnLabel('Progress'),
            ),
            GridColumn(
              columnName: 'OverallCount',
              width: isWebOrDesktop ? 140 : 140,
              label:
                  buildDataGridColumnLabel('Completed/Required/Total Readings'),
            ),
            GridColumn(
              columnName: 'NoOfBooksToBeRead',
              width: isWebOrDesktop ? 140 : 140,
              visible: false,
              label: buildDataGridColumnLabel('NoOfBooksToBeRead'),
            ),
            GridColumn(
              columnName: 'NumBooks',
              width: isWebOrDesktop ? 140 : 140,
              visible: false,
              label: buildDataGridColumnLabel('NumBooks'),
            ),
            GridColumn(
              columnName: 'Recording',
              width: isWebOrDesktop ? 130.0 : 130.0,
              label: buildDataGridColumnLabel('Recording'),
            ),
            GridColumn(
              columnName: 'Writing',
              width: isWebOrDesktop ? 120.0 : 120.0,
              label: buildDataGridColumnLabel('Writing'),
            ),
            GridColumn(
              columnName: 'CreateDate',
              width: 180,
              label: buildDataGridColumnLabel('CreateDate'),
            ),
            GridColumn(
              columnName: 'StartDate',
              width: 180,
              label: buildDataGridColumnLabel('StartDate'),
            ),
            GridColumn(
              columnName: 'DueDate',
              width: 180,
              label: buildDataGridColumnLabel('DueDate'),
            ),
            GridColumn(
              columnName: 'Id',
              width: 10,
              visible: false,
              label: buildDataGridColumnLabel('Id'),
            ),
          ],
        ),
      ),
    );
  }
}

class AssignmentDataGridSource extends DataGridSource {
  AssignmentDataGridSource({required List<ListAssingmentElement> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<String>(
                  columnName: 'Task', value: dataGridRow.assignment?.name),
              DataGridCell<String>(
                  columnName: 'Status',
                  value: dataGridRow.assignment?.status?.toUpperCase()),
              DataGridCell<int>(
                  columnName: 'OverallProgress',
                  value: dataGridRow.overallProgress),
              DataGridCell<int>(
                  columnName: 'OverallCount', value: dataGridRow.overallCount),
              DataGridCell<int>(
                  columnName: 'NoOfBooksToBeRead',
                  value: dataGridRow.assignment?.noOfBookToBeRead),
              DataGridCell<int>(
                  columnName: 'NumBooks',
                  value: dataGridRow.assignment?.numBooks),
              DataGridCell<bool>(
                  columnName: 'Recording', value: dataGridRow.recording),
              DataGridCell<bool>(
                  columnName: 'Writing', value: dataGridRow.writing),
              DataGridCell<int>(
                columnName: 'CreateDate',
                value: dataGridRow.assignment?.createDate,
              ),
              DataGridCell<int>(
                columnName: 'StartDate',
                value: dataGridRow.assignment?.startDate,
              ),
              DataGridCell<int>(
                columnName: 'DueDate',
                value: dataGridRow.assignment?.endDateUtc,
              ),
              DataGridCell<String>(
                columnName: 'Id',
                value: dataGridRow.assignment?.id,
              ),
            ]))
        .toList();
  }

  final box = Hive.box('appconfig');

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'CreateDate' ||
              dataGridCell.columnName == 'StartDate' ||
              dataGridCell.columnName == 'DueDate') {
            if (dataGridCell.value > 0) {
              return Container(
                  //alignment: Alignment.center,
                  //padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                DateFormat('yyyy-MM-dd kk:mm').format(
                    DateTime.fromMillisecondsSinceEpoch(dataGridCell.value)),
                overflow: TextOverflow.fade,
                style: Get.textTheme.bodySmall,
              ));
            } else {
              return Container(
                  //alignment: Alignment.center,
                  //padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                ' - ',
                overflow: TextOverflow.fade,
                style: Get.textTheme.bodySmall,
              ));
            }
          } else if (dataGridCell.columnName == 'Status') {
            String _status = dataGridCell.value
                .toString()
                .replaceAll('LIVE', 'OPEN')
                .replaceAll('PAST', 'CLOSED')
                .replaceAll('COMPLETED', 'CLOSED');
            return Container(
              //alignment: Alignment.center,
              //padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                _status,
                overflow: TextOverflow.fade,
                style: Get.textTheme.bodySmall,
              ),
            );
          } else if (dataGridCell.columnName == 'Task') {
            return Container(
              //alignment: Alignment.centerLeft,
              //padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: GestureDetector(
                onTap: () {
                  if (isTeacher) {
                    var id = row
                        .getCells()
                        .where((element) => element.columnName == 'Id')
                        .first
                        .value;
                    Get.to(() =>
                        HomeworkProgress(name: dataGridCell.value, id: id));
                  }
                },
                child: Text(
                  dataGridCell.value.toString(),
                  style: Get.theme.textTheme.titleLarge,
                  overflow: TextOverflow.fade,
                ),
              ),
            );
          } else if (dataGridCell.columnName == "OverallCount") {
            var noOfBookToBeRead = row
                .getCells()
                .where((element) => element.columnName == 'NoOfBooksToBeRead')
                .first
                .value;
            var numBooks = row
                .getCells()
                .where((element) => element.columnName == 'NumBooks')
                .first
                .value;
            return Container(
              //alignment: Alignment.center,
              //padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                "${dataGridCell.value}/$noOfBookToBeRead/$numBooks",
                softWrap: true,
                style: Get.textTheme.bodySmall,
                overflow: TextOverflow.fade,
              ),
            );
          } else if (dataGridCell.columnName == "OverallProgress") {
            return Container(
              //alignment: Alignment.center,
              //padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                dataGridCell.value.toString() + "%",
                softWrap: true,
                style: Get.textTheme.bodySmall,
                overflow: TextOverflow.fade,
              ),
            );
          } else if (dataGridCell.columnName == "Writing" ||
              dataGridCell.columnName == "Recording") {
            return Container(
              //alignment: Alignment.center,
              //padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                dataGridCell.value ? "Yes" : "No",
                softWrap: true,
                style: Get.textTheme.bodySmall,
                overflow: TextOverflow.fade,
              ),
            );
          } else {
            return Container(
                //alignment: Alignment.centerLeft,
                //padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
              dataGridCell.value.toString(),
              softWrap: true,
              overflow: TextOverflow.fade,
              style: Get.textTheme.bodySmall,
            ));
          }
        }).toList());
  }
}
